/*zWubMcx+l0Bp5Y+P2ZIAvjjPSpl9sf4SzZ2kuwM9XZOmB2e5P2iUtlN6lucgKrzq*/
import { ajax, getBusinessInfo, promptBox, toast, cardCache } from 'nc-lightapp-front';
import {
	delLine,
	copyLine,
	pasteLine,
	pasteToEndLine, generate, sendSpAndCancelSenSPPubFun
} from './billPubUtil.js';
import { cardBodyControl } from './buttonvisible.js';
import { getColvalues, getRowIds } from './billPubUtil';
import {
	checknoDisplayAfterEvent,
	checktypeAfterEvent
} from './specialFieldAfterEvent.js';
import { formulamsgHint, renderData, headAfterEventRenderData, bodyAfterEventRenderData, errorDeal } from '../afterEventPub/afterEventPubDeal';
import { moneyAndRateFields } from './specialFieldAfterEvent.js';

import { tableId, formId, leftarea } from '../../../gatheringbill/gatheringbill/card/constants';
import { toggleBtnStatus } from './MicroServiceSocket.js'
let { setDefData, getDefData, addCache, deleteCacheById, getCacheById, updateCache } = cardCache;

const dataSourcepay = 'fi.arap.paybill.20080EBM';

const dataSourceGat = 'fi.arap.gatheringbill.20060GBM';

export function afterEventFor36S3(that, props, moduleId, key, value, changedrows, i, record, g) {
	//如果当前输入值和上一次值相同，则直接返回，参照字段和非参照字段参数不同
	if (changedrows instanceof Array) {
		if (changedrows[0].newvalue.value == changedrows[0].oldvalue.value) {
			return;
		}
	}
	let index = 0;
	if (moduleId == that.formId) {
		index = 0;
	} else if (moduleId == that.tableId) {
		index = i;
	}
	let pagecode = that.pagecode;

	//表头编辑后事件
	if (moduleId == that.formId) {
		let data = {
			pageId: that.pagecode,
			event: that.props.createHeadAfterEventData(that.pagecode, that.formId, that.tableId, moduleId, key, value),
			uiState: that.props.getUrlParam('status')
		}
		let url;
		if (that.billType === "F2") {
			url = '/nccloud/arap/gatheringbill/cardheadafteredit.do'
		} else if (that.billType === "F3") {
			url = '/nccloud/arap/paybill/cardheadafteredit.do'
		}
		switch (key) {
			case 'customer':
				data = {
					pageId: pagecode,
					formEvent: props.createFormAfterEventData(pagecode, that.formId, that.tableId, key, value),
					colValues: getColvalues(that.props, that.tableId, ['pk_org', 'payaccount', 'pk_currtype', 'customer', 'buysellflag',
						'objtype', "direction", "pk_billtype", "top_billtype"].concat(moneyAndRateFields)),
					rowids: getRowIds(that.props, that.tableId),
					uiState: that.props.getUrlParam('status')
				};
				headFieldAfterRequest.call(that, data, key, changedrows, url)
				break;
			case 'pk_deptid_v':
				data = {
					pageId: pagecode,
					formEvent: props.createFormAfterEventData(pagecode, that.formId, that.tableId, key, value),
					colValues: getColvalues(that.props, that.tableId, ['pk_org', 'pk_deptid', 'pk_deptid_v', 'pk_currtype', 'customer', 'taxtype', 'buysellflag', 'objtype', "direction", 'billdate']),
					rowids: getRowIds(that.props, that.tableId),
					uiState: that.props.getUrlParam('status')
				};
				headFieldAfterRequest.call(that, data, key, changedrows, url)
				break;
			case 'pk_psndoc':
				data = {
					pageId: pagecode,
					formEvent: props.createFormAfterEventData(pagecode, that.formId, that.tableId, key, value),
					colValues: getColvalues(that.props, that.tableId, ['pk_org', 'pk_psndoc', 'pk_deptid', 'pk_deptid_v', 'isrefused', 'prepay', 'isdiscount', 'objtype', 'direction', 'agentreceivelocal']),
					rowids: getRowIds(that.props, that.tableId),
					uiState: that.props.getUrlParam('status')
				};
				headFieldAfterRequest.call(that, data, key, changedrows, url)
				break;
			case 'pk_currtype':
				data = {
					pageId: pagecode,
					formEvent: props.createFormAfterEventData(pagecode, that.formId, that.tableId, key, value),
					colValues: getColvalues(that.props, that.tableId, ["pk_org", "pk_group", "pk_currtype", "pk_billtype", "billdate", "rate",
						"buysellflag", "taxprice", "local_taxprice", "taxrate", "occupationmny", "money_bal", "local_money_bal",
						"globalcrebit", "globalnotax_cre", "globaltax_cre", "groupcrebit", "groupnotax_cre", "grouptax_cre",
						"local_money_cr", "local_notax_cr", "local_tax_cr", "money_cr", "notax_cr", "quantity_cr"]),
					rowids: getRowIds(that.props, that.tableId),
					uiState: that.props.getUrlParam('status')
				}
				headFieldAfterRequest.call(that, data, key, changedrows, url)
				//币种事件发送完要判断汇率
				//v2111 汇率控制发生变化，都走编辑前进行控制 currentTypeAfterFormEvents(that.formId, props, key);
				break;
			default:
				data = {
					pageId: pagecode,
					event: that.props.createHeadAfterEventData(pagecode, that.formId, that.tableId, moduleId, key, value),
					uiState: that.props.getUrlParam('status')
				}
				headFieldAfterRequest.call(that, data, key, changedrows, url)
				break;

		}
	}

	//表头币种编辑后事件
	if (moduleId == that.formId && key == "pk_currtype") {
		//v2111 汇率控制发生变化，都走编辑前进行控制 currentTypeAfterFormEvents(that.formId, props, key);
	}


	//表体编辑后事件
	if (moduleId == that.tableId) {
		//票据类型
		if (key == 'checktype') {
			checktypeAfterEvent(that.props, that.tableId, key, value, i);
		}
		//非元数据字段，票据号
		if (key == 'checkno_display') {
			checknoDisplayAfterEvent(that.props, that.tableId, key, value, i);
			key = 'checkno';
		}
		let url;
		if (that.billType === "F2") {
			url = '/nccloud/arap/gatheringbill/cardbodyafteredit.do'
		} else if (that.billType === "F3") {
			url = '/nccloud/arap/paybill/cardbodyafteredit.do'
		}

		ajax({
			url: url,
			data: {
				rowindex: 0,
				editindex: index,
				pageId: that.pagecode,
				tableId: that.tableId,
				changedrows: changedrows,
				body: props.cardTable.getDataByIndex(that.tableId, index),
				formEvent: props.createFormAfterEventData(that.pagecode, that.formId, that.tableId, key, value),
				uiState: that.props.getUrlParam('status')
			},
			async: false,
			success: (res) => {
				//渲染数据
				bodyAfterEventRenderData(that, res);

				if (that.props.getUrlParam('type') == 'transfer') {
					that.synTransferData();
				}
				//表体改变表头税率编辑性
				if (i == 0 && key == 'pk_currtype') {
					//v2111 汇率控制发生变化，都走编辑前进行控制 currentTypeAfterFormEvents(that.formId, props, 'pk_currtype');
				}
				//编辑公式提示
				formulamsgHint(that, res);
			},
			error: (res) => {
				let str = res.message
				if (str.substring(0, 16) == 'convertException') {
					promptBox({
						color: 'warning',
						title: that.state.json['gatheringbill-000000'] /* 国际化处理： 折算误差*/,
						content: str.substring(16, str.length),
						closeByClickBackDrop: false,
						beSureBtnClick: () => {
							afterTableEvent(that, props, i, that.pagecode, moduleId, key, changedrows, 'sure', index, value, url);
						},
						cancelBtnClick: () => {
							afterTableEvent(that, props, i, that.pagecode, moduleId, key, changedrows, 'cancel', index, value, url);
						}
					});
				} else {
					that.props.cardTable.setValByKeyAndRowId(that.tableId, i, key, changedrows);
					toast({ color: 'danger', content: str });;
				}
			}
		});

	}

}
export function headFieldAfterRequest(requestData, key, changedrows, url) {
	ajax({
		url: url,
		data: requestData,
		async: false,
		success: (res) => {
			//渲染数据
			headAfterEventRenderData(this, res);

			if (key == 'pk_org') {
				let pk_org = this.props.form.getFormItemsValue(this.formId, 'pk_org').value;
				if (pk_org) {
					this.props.resMetaAfterPkorgEdit();
					this.state.buttonfalg = true;
				} else {
					this.state.buttonfalg = null;
				}
				this.toggeleShow436S3();
			}
			//编辑公式提示
			formulamsgHint(this, res);

		},
		error: (res) => {
			errorDeal(this, res, changedrows, key);
		}
	});
}
function afterTableEvent(that, props, i, pagecode, moduleId, key, changedrows, isCalculateConvert, index, value, url) {
	ajax({
		url: url,
		data: {
			rowindex: 0,
			editindex: index,
			pageId: pagecode,
			changedrows: changedrows,
			tableId: that.tableId,
			body: props.cardTable.getDataByIndex(that.tableId, index),
			formEvent: props.createFormAfterEventData(pagecode, that.formId, that.tableId, key, value),
			uiState: that.props.getUrlParam('status'),
			isCalculateConvert: isCalculateConvert
		},
		async: false,
		success: (res) => {
			//渲染数据
			bodyAfterEventRenderData(that, res);
			if (that.props.getUrlParam('type') == 'transfer') {
				that.synTransferData();
			}
			//表体改变表头税率编辑性
			if (i == 0 && key == 'pk_currtype') {
				//v2111 汇率控制发生变化，都走编辑前进行控制 currentTypeAfterFormEvents(that.formId, props, 'pk_currtype');
			}
			//编辑公式提示
			formulamsgHint(that, res);

		}
	});
}
//按钮点击事件
export function buttonClick4cmp36S3(_this, props, id) {
	let billType = _this.billType;
	let dataSource = billType == 'F3' ? dataSourcepay : dataSourceGat;
	switch (id) {
		case 'Save':
			{

				let result = _this.props.validatePageToToast([
					{
						name: _this.formId,
						type: "form",
					},
					{
						name: _this.tableId,
						type: "cardTable",
					}
				]);
				if (result && !result.allPassed) {
					return;
				}
				let url;
				let cardData = _this.props.createMasterChildData(_this.pagecode, _this.formId, _this.tableId)
				if (_this.props.getUrlParam('status') === "add") {
					url = '/nccloud/arap/arappub/releasetoarapsave.do'  //到账通知保存，为什么不和单据的保存走一个请求？0000
				} else {
					url = '/nccloud/arap/arappub/save.do'
				}
				let data = {
					cardData: cardData,
					billType: _this.billType,
					uiState: _this.props.getUrlParam('status'),
					top_billtype: '36S3'
				}
				let callback = () => {
					ajax({
						url: url,
						data: data,
						success: (res) => {
							if (res.success) {
								setValue.call(_this, props, res)
							}
						}
					})
				}
				//调用验证公式
				_this.props.validateToSave(cardData, callback, { table1: 'cardTable' }, 'card');
			}
			break;
		case 'Cancel':
			{
				if (_this.props.getUrlParam('pks') || _this.props.getUrlParam('id')) {
					_this.props.setUrlParam({ status: 'browse' });
					let id = _this.props.getUrlParam('id') ? _this.props.getUrlParam('id') : _this.props.getUrlParam('pks');
					let cardData = getCacheById(id, dataSource);

					if (cardData) {
						_this.props.beforeUpdatePage();//打开开关
						_this.props.form.EmptyAllFormValue(_this.formId);
						_this.props.cardTable.setTableData(_this.tableId, { rows: [] });
						_this.props.form.setAllFormValue({ [_this.formId]: cardData.head[_this.formId] });
						_this.props.cardTable.setTableData(_this.tableId, cardData.body[_this.tableId]);
						_this.props.cardTable.setStatus(_this.tableId, 'browse');
						_this.props.form.setFormStatus(_this.formId, 'browse');
						_this.props.updatePage(_this._this, _this.tableId);//关闭开关
						_this.toggeleShow436S3(cardData);
					} else {
						_this.props.beforeUpdatePage();//打开开关
						_this.props.form.EmptyAllFormValue(_this.formId);
						_this.props.cardTable.setTableData(_this.tableId, { rows: [] });
						_this.props.cardTable.setStatus(_this.tableId, 'browse');
						_this.props.form.setFormStatus(_this.formId, 'browse');
						_this.props.updatePage(_this._this, _this.tableId);//关闭开关
						_this.toggeleShow436S3();
					}

				} else {
					_this.props.beforeUpdatePage();//打开开关
					_this.props.form.EmptyAllFormValue(_this.formId);
					_this.props.cardTable.setTableData(_this.tableId, { rows: [] });
					_this.props.cardTable.setStatus(_this.tableId, 'browse');
					_this.props.form.setFormStatus(_this.formId, 'browse');
					_this.props.updatePage(_this._this, _this.tableId);//关闭开关
					_this.props.setUrlParam({ status: 'browse' })
					_this.toggeleShow436S3()
				}
			}
			break;
		case 'Edit':
			if (_this.props.getUrlParam('id') && _this.props.form.getFormItemsValue(_this.formId, _this.pkName).value) {
				ajax({
					url: '/nccloud/arap/arappub/edit.do',
					data: {
						pk_bill: _this.props.getUrlParam('id'),
						billType: _this.billType
					},
					success: (res) => {
						if (res.success) {
							props.setUrlParam({ status: 'edit' })
							_this.toggeleShow436S3(res)
						}
					}
				})
			} else {
				props.setUrlParam({ status: 'add' })
				_this.toggeleShow436S3()
			}
			break;
		case 'Quit':
			_this.props.linkTo('/cmp/informerrelease/SscRelease/list/index.html', {
				appcode: '36070AIPSSC',
				pagecode: '36070AIPSSC_L01',
			})
			break;
		case 'QuitRefund':
			_this.props.linkTo('/cmp/informerrelease/SscRelease/list/index.html', {
				appcode: '36070AIPSSC',
				pagecode: '36070AIPSSC_L01',
			})
			break;
		case 'SaveAndCommit':
			_this.saveBill('/nccloud/arap/arappub/saveandcommit.do');
			break;
	    case 'Commit':
			_this.Info.tipUrl = '/nccloud/arap/arappub/commit.do';
			_this.commitAndUncommit();
			break;
		case 'Uncommit':
			_this.Info.tipUrl = '/nccloud/arap/arappub/uncommit.do';
			_this.commitAndUncommit();
			break;
		case 'CopyLine':
			if (copyLine(_this, dataSource)) {
				_this.setState(
					{
						buttonfalg: false
					},
					() => {
						cardBodyControl(props, _this.state.buttonfalg, _this);
						let isrefund = props.form.getFormItemsValue(_this.formId, 'isrefund') ? props.form.getFormItemsValue(_this.formId, 'isrefund').value : false
						if (isrefund) {
							props.button.setButtonVisible(['AddLine', 'Insert_inner'], false);
						}
					}
				);
			}
			break;
		case 'DelLine':
			delLine(_this);
			//删行之后控制肩部按钮
			_this.onSelected();
			break;
		case 'PasteLine': //粘贴行
			pasteLine(_this);
			break;
		case 'PasteToEndLine': //粘贴行到末尾
			pasteToEndLine(_this, dataSource);
			break;
		case 'CancelLine': //行取消
			_this.setState(
				{
					buttonfalg: true
				},
				() => {
					cardBodyControl(props, _this.state.buttonfalg, _this);
					let isrefund = props.form.getFormItemsValue(_this.formId, 'isrefund') ? props.form.getFormItemsValue(_this.formId, 'isrefund').value : false
					if (isrefund) {
						props.button.setButtonVisible(['AddLine', 'Insert_inner'], false);
					}
				}
			);
			//取消之后控制肩部按钮
			_this.onSelected();
			break;
		case 'AddLine'://增行
			if (_this.props.form.getFormItemsValue(_this.formId, 'pk_org_v').value != null) {
				let rowNum = props.cardTable.getNumberOfRows(_this.tableId);
				let url = billType == 'F3' ? '/nccloud/arap/paybillpub/addline.do' : '/nccloud/arap/gatheringbill/addline.do';
				ajax({
					url: url,
					data: _this.props.createMasterChildData(_this.getPagecode(), _this.formId, _this.tableId),
					success: (res) => {
						if (res.data) {
							if (res.data.head) {
								_this.props.form.setAllFormValue({ [_this.formId]: res.data.head[_this.formId] });
							}
							if (res.data.body) {
								_this.props.cardTable.addRow(
									_this.tableId,
									rowNum,
									res.data.body[_this.tableId].rows[0].values
								);
							}
						}
					}
				});
			}
			break;
		default:
			break;
	}
}

export function setValue(props, res) {
	if (res) {
		toggleBtnStatus.call(this, res, 'card_head');
	}
	let billType = this.billType;
	let dataSource = billType == 'F3' ? dataSourcepay : dataSourceGat;
	if (res.data.head && res.data.head[formId]) {
		props.form.setAllFormValue({ [formId]: res.data.head[formId] });
	}
	//if(res.data.head)
	if (res.data.body && res.data.body[tableId]) {
		if (props.getUrlParam('status') === "add") {
			props.cardTable.setTableData(tableId, res.data.body[tableId]);
		} else {
			props.cardTable.updateDataByRowId(tableId, res.data.body[tableId]);
		}
	}
	let pk_bill = this.props.form.getFormItemsValue(this.formId, this.pkName).value
	let newCardData = this.props.createMasterChildData(
		this.pagecode, this.formId, this.tableId
	);
	if (props.getUrlParam('status') == 'add') {
		addCache(pk_bill, newCardData, formId, dataSource)
	} else {
		updateCache(this.pkname, pk_bill, newCardData, formId, dataSource);
	}
	this.props.button.setButtonVisible(['TempSave'], false);
	props.transferTable.setTransformFormStatus(leftarea, {
		status: true,
		// onChange: (current, next, currentIndex) => {
		// 	toast({ color: 'success', content: this.state.json['arappub-000002'] });/* 国际化处理： 操作成功*/
		// 	this.transferIndex = currentIndex + 1;
		// 	this.isNeedSelect = true
		// 	props.transferTable.setTransferListValueByIndex(
		// 		leftarea,
		// 		newCardData,
		// 		currentIndex
		// 	)
		// }
	})
}
export function fieldVisable(_this, formId, tableId, billType) {
	let trueCol = ["invoiceno", "productline", "pk_subjcode", "subjcode"];
	let falseCol = ["material", "taxcodeid", "taxrate"];
	if (billType == "F2") {
		trueCol.push("project");
		falseCol.push("local_tax_cr", "local_notax_cr");
	} else {
		trueCol.push("isurgent");
		falseCol.push("direct_checkno", "notax_de", "groupnotax_de", "globalnotax_de");
	}
	_this.props.form.setFormItemsVisible(formId, { "isrefund": false });
	_this.props.cardTable.hideColByKey(tableId, falseCol);
	_this.props.cardTable.showColByKey(tableId, trueCol);
}
/*zWubMcx+l0Bp5Y+P2ZIAvjjPSpl9sf4SzZ2kuwM9XZOmB2e5P2iUtlN6lucgKrzq*/